<style>
.btn-min{
	min-width: 77px;
}
.share-bar{
	font-size: 0.8em;
}

.pr-detail-title{
    overflow: hidden;
}
	
/* 商品详情，评价  */
.product-detail header {
  display: -webkit-box;
  display: box;
  height: 2.857em;
  border: 1px solid #ccc;
  border-top: none;
  border-bottom: none;
  background-color: #e9e9e9;
  box-shadow: 0 1px 2px rgba(0,0,0,.2);
  text-align: center;
  line-height: 2.857em;
}

.product-detail header a {
  display: block;
  border-top: 1px solid #ccc;
  -webkit-box-flex: 1;
}

.product-detail header a.current {
  background-color: #fff;
  border-top-color: #b10000;
  border-top-width: 2px;
}

.product-detail .wrap {
  overflow: hidden;
  border: 1px solid #ccc;
  border-top: none;
  background-color: #fff;
  word-wrap: break-word;
  padding-top: 1em;
}

#product-content{
	margin-bottom: 10px;
}

#product-content p{
	padding: 0 10px 10px;
}

.product-comment li {
  border-bottom: 1px solid #ccc;
  padding-bottom: .3em;
  margin-bottom: .7em;
  margin: 0 10px 10px;
  border: #ddd solid 1px;
  padding: 10px;
  border-radius: 3px;
}

.product-comment li .user {
  margin-top: .8em;
  font-size: .8em;
  padding-top: 5px;
  border-top: #ddd dashed 1px;
}

.product-comment li .user time {
  float: right;
  color: #555;
}
#product-comment-list {
	text-align: center;
	padding: 20px;
}
del{
    color: #999;
    font-size: 70%;
}
.float-right{
    float: right;
}
.color-red{
    color: red;
}
.text-underline{
    text-decoration: underline;
}
</style>

<!-- TOPBAR -->
<header class="top-bar flex-row">
  <span class="row-item row-item-auto top-bar-back" onclick="window.history.back()">返回</span>
  <h3 class="row-item top-bar-name">{$shopGoods.name}</h3>
  <a class="row-item row-item-auto top-bar-menu" href="{$config.url}">主页</a>
</header>

<include file="headerBar"/>

<!-- 商品图片 -->
<section class="pr-detail-header">

<style type="text/css">
.gh-tip {
	position: relative;
}
</style>
  
  <div class="swiper-container">
    <figure class="tc swiper-wrapper">
      <volist name="shopGoods['images']" id="vo">
        <div class="swiper-slide">
          <img src="{$vo}" alt="">
        </div>
      </volist>
    </figure>  
  </div>

</section>

<section class="pr-detail pr-detail-info">

  <header class="flex-row">
    <div class="row-item row-item-6"><notempty name="shopGoods.description"><h3>{$shopGoods.description}</h3></notempty></div>
  </header>
  <header class="flex-row">
    <div class="row-item row-item-6">
      <p class="pr-info-now-price"><small>微信价:￥<if condition="$user['type'] eq 2 && $shopGoods['dealer_price'] gt 0">{$shopGoods.dealer_price}<else/>{$shopGoods.price}</if></small></p>
      <gt name="shopGoods.high_price" value="0"><p class="pr-info-now-price"><del>原价:￥{$shopGoods.high_price}</del></p></gt>
    </div>

    <div class="row-item row-item-4">
      <p class="pr-info-saled">{$shopGoods['saled_count']+$shopGoods['saled_base']}人已购买</p>
    </div>  
  </header>
  
  <div class="pr-info-freight">
    <p class="clearfix"><a id="btn-distribution" class="float-right btn btn-action-red">我要推广</a>运费：￥{$shopGoods.carriage}</p>
  </div>
</section>

<notempty name="shopGoods.donate_money_real">
    <section class="pr-detail">
        <h5 class="pr-detail-content color-red">该商品正在参加公益捐赠活动，购买献爱心！</h5>
        <section class="pr-detail-content color-red">
            <p>您每购买一件此商品，我们将向公益基金捐赠 <strong>{$shopGoods.donate_money_real}</strong> 元。</p>
            <p>该商品已经累计捐赠 <strong>{$shopGoods.donate_sum}</strong> 元。</p>
        </section>
        <section class="pr-detail-content">
            <p><a href="__CONTROLLER__/donateProjectLists/sid/{$sid}">------&gt;查看公益捐赠项目</a></p>
        </section>
    </section>
</notempty>

<section class="pr-detail">
  
  <h5 class="pr-detail-title">选择商品类型</h5>

  <section id="pr-buy-check" class="pr-detail-content">
      
    <form id="pr-form" method="post" action="{:U('DisShopOrder/confirmOrder')}">

      <!-- 类型 -->
      <foreach name="shopGoods.attrs_cfg" item="vo" key="key">

      <dl class="pr-check-item pr-check-attr">
        <dt class="pr-check-key" data-null="请选择{$key}">{$key}:</dt>
        <dd class="pr-check-value">
          <foreach name="vo" key="key1" item="vo1">
          <input hidden type="radio" id="{$key1}|{$vo1}" name="attrs[{$key}]" value="{$vo1}">
          <label class="pr-check-value-item" data-value="{$key1}|{$vo1}" for="{$key1}|{$vo1}">{$vo1}</label>
          </foreach>
        </dd>
      </dl>

      </foreach>
      
      <!-- 购买数量 -->
      <dl class="pr-check-item">
        <dt class="pr-check-key">数量:</dt>
        <dd class="pr-check-value">
          <p class="pr-num flex-row">
            <span id="buy-num-minus" class="pr-num-minus row-item row-item-3" data-type="m">-</span>
            <input id="buy-num" class="pr-num-input row-item row-item-4" name="quantity" readonly="readonly" value="1">
            <span id="buy-num-plus" class="pr-num-plus row-item row-item-3" data-type="p">+</span>
          </p>
        </dd>
      </dl>
      
      <input type="hidden" name="id" value="{$shopGoods.id}">
      <input type="hidden" name="sid" value="{$sid}">  

    </form>
    
  </section>

</section>

<section id="pr-action" class="pr-buy-action">
	<p>
		<if condition="$user['id'] eq 29">
		  <a id="pr-buygifts" class="btn btn-min btn-action-red" style="background-color: #DE2727;" href="javascript:;" data-jump="1" action-url="{:U('DisShopGiftsOrder/confirmOrder')}">我要送礼</a>
		</if>
		
		<if condition="$shopGoods['is_seckill'] || ($shopGoods['price'] eq 0)">
		<else/>
		  <a id="pr-addto-cart" class="btn btn-min btn-action-orange" href="javascript:;" data-jump="0" <if condition="$shopGoods['timing_shelves'] neq 0">disabled='disabled'</if>>加入购物车</a>
		</if>
		
		<if condition="$shopGoods['timing_shelves'] neq 0">
		<span id="desc-time" class="row-item" style="line-height: 38px;"></span>
		<script type="text/javascript">
		var now = {:time()*1000},
			toTime = {$shopGoods['timing_shelves']}*1000,
			subTime = toTime-now,
			unit = ['天', '时', '分', '秒'];
		
		function calcTime( subTime ) {
			var d = [24*60*60*1000, 60*60*1000, 60*1000, 1000];
			var dt = [];
			for ( var i = 0; i < d.length; i++ ) {
				dt[i] = deTime(subTime, d[i]);
				subTime = subTime - dt[i][0]*d[i];
			}
			return dt;
		}
			
		function deTime(subTime, s) {
			return [parseInt(subTime / s), subTime % s];
		}
		
		function startTime() {
			var timer = setInterval(function() {
				now = now + 1000;
				var subTime = toTime-now;
				var d = calcTime( subTime );
				var timeString = "";
				if ( subTime <= 0 ) {
					timeString = "已开始";
					clearInterval(timer);
					$("#pr-buynow").removeAttr("disabled");
					$("#pr-addto-cart").removeAttr("disabled");
					$("#desc-time").remove();
				} else {
					var zero = true;
					for ( var i=0; i<d.length; i++ ) {
						if( d[i][0]!=0 && zero ) {
							zero = false;
						}
						if ( !zero ) {
							timeString+="<font color='red' size='6'>"+d[i][0]+"</font>"+unit[i];
						}
					}
				}
				$("#desc-time").html(timeString);
			}, 1000);
		}
		startTime();
		</script>
		</if>
	    <a id="pr-buynow" class="btn btn-min btn-action-red" href="javascript:;" data-jump="1" <if condition="$shopGoods['timing_shelves'] neq 0">disabled='disabled'</if>>立即购买</a>
	</p>
</section>

<section class="product-item product-detail" style="margin-top:10px;">
    <header id="product-tab">
      <a href="javascript:;" class="current" data-id="product-content">商品详情</a>
      <a href="javascript:;" data-id="product-comment">商品评价</a>
    </header>
    <div class="wrap pd10" id="product-content" style="">
      {$shopGoods.content}
    </div>
    <div class="wrap pd10" id="product-comment" style="display:none;">
    <!-- 评论start -->
  	<div id="product-comment-list">暂无评论</p>
    <!-- 评论end -->
    </div>
</section>

<link rel="stylesheet" href="__COMMON__/swiper/idangerous.swiper.css">
<script src="__PUBLIC__/Static/js/simapp.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
  (function(){
      
      $("#btn-distribution").click(function(){
          simapp.tips("分享给朋友或朋友圈吧，朋友购买后，你就可以获得提成啦！");
      })
    
    // 选择属性
    $("#pr-buy-check input[type=radio]").on("change", selectAttr);

    function selectAttr() {
      var labels = $(this).siblings("label");
      $(labels).each(function(){
        $(this).removeClass("checked");
      });
      $(this).next().addClass("checked");
    };

    // 改变商品数量
    var buyNum = $("#buy-num");
    $("#buy-num-minus, #buy-num-plus").on("tap", changeNum);

    function changeNum() {

      var v = $(buyNum).val()*1,
          type = $(this).attr("data-type");

      if ( type === "m" ) {
        v <= 1 ? APP.alert("数量真的已经不能再少了T^T")
               : $(buyNum).val(v - 1);
      } else if ( type === "p" ) {
        $(buyNum).val(v + 1);
      };

    };

    // 加入购物车和购买
    $("#pr-addto-cart").on("tap", function() {
      var jump = $(this).attr("data-jump")*1;
      isAllChecked(function(){
        insertCart(jump);
      });
    });
    
    // 立即购买
    $("#pr-buynow").on("tap", function() {
      isAllChecked(function(){
    	  $('#pr-form').submit();
      });
    });
    
    // 立即送礼
    $("#pr-buygifts").on("tap", function() {
      $('#pr-form').attr("action", $(this).attr("action-url"));
      isAllChecked(function(){
    	  $('#pr-form').submit();
      });
    });
    
    function insertCart(jump) {
      var postData = $("#pr-form").serialize();
      APP.showLoading();

      $.post("{:U('DisShopCart/addItem')}", postData, function(response) {
        APP.hideLoading();
        if ( response.error === 0 ) {
          jump ? $("#pr-form").submit() : insertSuccess();
        } else {
          APP.alert(response.msg);
        };
      });
    };

    function insertSuccess() {
      require(["modal"], function(M) {
        M.confirm({
          title: "添加到购物车",
          text: "该商品已成功添加到购物车",
          buttons: [{
            text: "继续逛",
            close: true
          }, {
            text: "去购物车",
            click: function() {
              window.location.href = "{:url(null, 'DisShopCart', 'showCart', 'sid='.$sid.'&qid='.$qid)}";
            }
          }]
        })
      });
    };

    function isAllChecked( callback ) {

      var checkedAll = true;

      $(".pr-check-attr").each(function() {
        
        var checked = false;

        $(this).find("input[type='radio']").each(function() {
          $(this).prop("checked") && ( checked = true );
        });

        if ( !checked ) {
          var info = $(this).children(".pr-check-key").attr("data-null");
          APP.alert(info);
          checkedAll = false;
          return false;
        };

      });

      checkedAll && callback && callback();
      
    };    
    
    var w = $(".swiper-container").width()/3;
    $(".swiper-container,.swiper-wrapper,.swiper-slide").height(w*1.5);
    require(['__COMMON__/swiper/idangerous.swiper.js'], function(S) {
      new S(".swiper-container", {
        mode:'horizontal',
        autoplay:5000
      });
    });
    
    
    // 获取商品评价内容
    var productId = {$shopGoods.id};
    window.p = 1;
    window.rateLoad = 0;
    window.moreRate = function(showAlert) {
        $.ajax({
        	type:'POST',
        	url:"{:U('Home/DisShopRate/moreRate')}",
        	data: {
        		'sid': "{$sid}",
        		"product_id": "{$shopGoods.id}",
        		'p': window.p++
        	},
        	success: function(data) {
        		if( data.extra.length==0 ) {
        			window.p--;
        			if(showAlert){
        			    APP.alert('没有更多了');
        			}
        		}
        		data.extra && showComment(data.extra);
        	}
        })
    }
    
    function showComment( data ) {
		
      if(data==null || data.length==0){
          return;
      }
      var html = "";
      for ( var i = 0; item = data[i]; i++ ) {
        html += "<li><p>" + item.content + "</p>"
               +"<div class='user clearfix'><span>" + item.userNickName + "</span><time>" + new Date(item.create_time*1000).Format("yyyy-MM-dd hh:mm:ss") + "</time></div>"
               +"</li>";
      };
      if ( !window.rateLoad ) {
    	  document.getElementById( "product-comment" ).innerHTML = "<ul class='product-comment'>" + html + "</ul><a href=\"javascript:return false;\" style=\"width: 172px;margin: 20px auto;clear: both;float: none;display: block;\" onclick=\"moreRate(1);\">加载更多&gt;&gt;</a>";
      } else {
    	  $(".product-comment").append(html);
      }
      window.rateLoad = 1;
    };
    
    Date.prototype.Format = function(fmt) { 
      var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
      }; 
      if(/(y+)/.test(fmt)) 
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
      for(var k in o) 
        if(new RegExp("("+ k +")").test(fmt)) 
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
      return fmt; 
    };

    // 切换商品详情和评价
    var productTab = document.querySelectorAll('#product-tab a');
    [].forEach.call(productTab, function(obj){
      obj.addEventListener('click', clickTab, false);
    });

    // 切换Tab
    function clickTab() {
      [].forEach.call(productTab, function(obj){
        obj.className = '';
        document.getElementById( obj.getAttribute('data-id') ).style.display = 'none';
      });
      this.className = 'current';
      document.getElementById( this.getAttribute('data-id') ).style.display = 'block';
    }

    moreRate(0);
  })();
</script>